package com.zhiyou100.shiro;

import com.zhiyou100.model.Permission;
import com.zhiyou100.model.Role;
import com.zhiyou100.model.User;
import com.zhiyou100.serice.UserSerice;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyRealm extends AuthorizingRealm{

    @Autowired
    private UserSerice serice;
    //这个是关于身份认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        List<String> roles = serice.findRoleById(user.getId());
        List<String> permissions = serice.findPermissionById(user.getId());
        SimpleAuthorizationInfo  simp = new SimpleAuthorizationInfo();
        simp.addRoles(roles);
        simp.addStringPermissions(permissions);
        return simp;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到邮箱/账号
        String email = (String) token.getPrincipal();

        System.out.println("MyRealm执行了"+email);
        //得到密码
        String password = new String ((char[])token.getCredentials());
        //通过邮箱来查用户
        User user = serice.findUserByEmail(email);
        System.out.println("Realm中的user :" +user);
        //判断这个用户存在
        if(user == null || user.getId() == null || user.getId().equals("")){
            //用户不存在抛一个异常,给controller
            throw new AuthenticationException();
        }
        System.out.println("日志  ==>  realm中打印的user对象 : "+user);
        //得到这个用户密码加密的盐值
        String saly = user.getCalt();
        //转换为盐值对象
        ByteSource byteSource = ByteSource.Util.bytes(saly);
        //进行身份和密码认证,密码进行加密次数在applicationContext.xml中设置
        return new SimpleAuthenticationInfo(user,user.getPassword(),byteSource,getName());
    }
}
